from  tkinter import * #导入TKinter模块
from socket import *
import threading

class MainPage(object):
    def __init__(self,master=None,name):
        self.name = name
        self.root = master #定义内部变量root
        self.root.geometry("800x600") #设置窗口尺寸
        self.bufsize = 1024  #定义缓冲大小
        self.serveraddr = ('127.0.0.1',13141) # 服务器ip,端口，元祖形式
        self.udpClient = socket(AF_INET,SOCK_DGRAM) #创建客户端
        self.content = list()
        self.createPage()
    def createPage(self):
        self.frame1=Frame(self.root)
        self.frame2=Frame(self.root)
        self.frame1.pack()
        self.frame2.pack(side=BOTTOM)
        self.inp_text=Entry(self.frame2,width=60) #创建输入框（输入聊天内容）
        self.btn = Button(self.frame2,text="发送",width=15,command=self.sendmsg) #绑定获取文本框内容方法
        self.inp_text.pack(side=LEFT)
        self.btn.pack(side=LEFT)
    def sendmsg(self):
        self.get_inp = self.inp_text.get() #获取输入框内容
        if self.get_inp:
            self.get_inp = self.name+':' + self.get_inp #添加姓名标示
            self.get_inp = self.get_inp.encode(encoding="utf-8")
            self.udpClient.sendto(self.get_inp,self.serveraddr) # 发送数据
            self.inp_text.delete('0','end')
    def recvmsg(self):
        self.data,self.addr = self.udpClient.recvfrom(self.bufsize) #接收数据和返回地址
        self.data = self.data.decode(encoding="utf-8")
#        self.content.append(self.data+'\n')
#        self.ss=''.join(self.content)
        return self.data
 
class myThread(threading.Thread):
    def __init__(self,id,mypage = None):
        self.mypage = mypage    #获取MainPage的实例化对象
        threading.Thread.__init__(self)
        self.id=id
    def run(self):
        if self.id == 1:
            while True:
                self.ss = self.mypage.recvmsg()
                if  self.ss:
                    print(self.ss)
                    self.mypage.text=Label(self.mypage.frame1,text=self.ss) #创建聊天内容标签
                    self.mypage.text.pack(side=TOP,padx=1)

